package cat.joronya.supermanager.service;

import java.io.ByteArrayOutputStream;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.htmlcleaner.ContentNode;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;

import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.util.Log;
import cat.joronya.supermanager.Supermanager;
import cat.joronya.supermanager.Supermanager.PrivateLeagueTeam;
import cat.joronya.supermanager.privateleague.PrivateLeague;
import cat.joronya.supermanager.team.Team;

/**
 * Recuperem el llistat de private leagues.
 * 
 * @author pol
 */
public class PrivateLeaguesSync extends Object// AsyncTask<String,Void,Integer>
{
	private static final String TAG = "supermanager";

	// el service
	private SupermanagerService service;

	// el client http on fer les peticions
	private DefaultHttpClient client = null;

	// status de retorn
	public int status = -1;

	// private leagues GET
	private static final String PRIVATE_LEAGUES_LIST_GET = InitSync.BASE_URL
			+ "/ligasprivadas.php";
	// private league teams
	private static final String PRIVATE_LEAGUE_TEAMS = InitSync.BASE_URL
			+ "/verprivada.php";

	// XPATHs per treure dades de les pagines
	// private leagues XPATH
	private static final String PRIVATE_LEAGUES_XPATH = "//td[@background='gif/ligaprivada.gif']";
	// private league teams XPATH
	private static final String PRIVATE_LEAGUE_TEAMS_XPATH = "//td[@background='gif/clasificacionpos.gif']";
	// jornada
	private static final String PRIVATE_LEAGUE_DAY_XPATH = "//font[@class='blanca16']";

	// dades extretes de les pagines
	public ArrayList<PrivateLeague> privateLeagues;

	/**
	 * Constructor amb el intentService que el crida.
	 * 
	 * @param intentService
	 */
	public PrivateLeaguesSync(SupermanagerService service,
			DefaultHttpClient client) {
		this.service = service;
		this.client = client;
	}

	@SuppressWarnings("rawtypes")
	protected void execute()// doInBackground(String... params)
	{
		try {
			// checkejem per connectivitat
			ConnectivityManager cm = (ConnectivityManager) service
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			boolean online = cm.getActiveNetworkInfo()
					.isConnectedOrConnecting();

			if (!online)
				throw new ConnectivityException();

			// empty array of private leagues
			privateLeagues = new ArrayList<PrivateLeague>();

			HttpGet plHttpGet = new HttpGet(PRIVATE_LEAGUES_LIST_GET);
			HttpResponse response = client.execute(plHttpGet);
			HtmlCleaner cleaner = new HtmlCleaner();

			ByteArrayOutputStream os = new ByteArrayOutputStream();
			response.getEntity().writeTo(os);
			String privateLeagueslPage = os.toString(HTTP.ISO_8859_1);
			TagNode node = cleaner.clean(privateLeagueslPage);

			// cerquem les lligues
			Object[] tdPL = node.evaluateXPath(PRIVATE_LEAGUES_XPATH);
			TagNode tagPLHeader = (TagNode) tdPL[0];
			TagNode tagPLTable = tagPLHeader.getParent().getParent();
			
			// trs de lligues privades per veure si n'hi ha
			List trs = tagPLTable.getChildren();
			
			if( trs.size() >= 3 )
			{
				// llistem els equips, diferents trs
				for (Object objTr : tagPLTable.getChildren()) 
				{
					// descartem el tr del titular
					if (tagPLHeader.getParent().equals(objTr))
						continue;

					// els tds
					List tds = ((TagNode) objTr).getChildren();

					// primer td
					TagNode td0 = (TagNode) tds.toArray()[0];

					// si es l'ultim acabem, es a dir te
					// background='gif/ligasabajo.gif'
					if ("gif/ligasabajo.gif".equals(td0
							.getAttributeByName("background")))
						continue;

					// si no hi han lligues i trobem missatge, continue
					List td0Childs = td0.getChildren();
					if( td0Childs.toArray()[0] instanceof ContentNode )
					{
						ContentNode contentNode = (ContentNode)td0Childs.toArray()[0];
						String contentString = contentNode.toString();
						if( "En estos momentos no tienes ningún equipo participando en Ligas Privadas.".equals(contentString) )
							continue;
					}
					
					// inicialitzem private league
					PrivateLeague pl = new PrivateLeague();
					for (Object td0Child : td0.getChildren()) {
						TagNode a = (TagNode) td0Child;
						if ("a".equals(a.getName())) {
							String href = a.getAttributeByName("href");
							String id = href.replaceFirst("verprivada.php.id_pri=",
							"");
							pl.setId(id);
							for (Object aContent : a.getChildren()) {
								if (aContent instanceof ContentNode)
									pl.setName(aContent.toString());
							}
						}
					}

					// segon td
					TagNode td1 = (TagNode) tds.toArray()[1];
					for (Object td1Child : td1.getChildren()) {
						if (td1Child instanceof ContentNode)
							pl.setNumberOfTeams(td1Child.toString());
					}

					// guardem al llistat de private leagues
					privateLeagues.add(pl);
				}

				// de cada private league parsejem el detall point, general i broker
				for (PrivateLeague pl : privateLeagues) {
					getPrivateLeagueTeams(pl);
					getPrivateLeagueTeamsGeneral(pl);
					getPrivateLeagueTeamsBroker(pl);
				}
			}

			// parsejat ok
			status = Supermanager.PRIVATE_LEAGUES_PARSED_OK;
			Log.d(TAG, "PrivateLeaguesSync status: PRIVATE_LEAGUES_PARSED_OK - "+status);
			return;
		} catch (ConnectivityException ce) {
			// error de connectivitat
			status = Supermanager.CONNECTIVITY_ERROR_STATUS;
			Log.d(TAG, "PrivateLeaguesSync status: CONNECTIVITY_ERROR_STATUS - "+status);
			return;
		} catch (Exception e) {
			// altre error, notifiquem i anem offline
			status = Supermanager.OTHER_ERROR_STATUS;
			Log.d(TAG, "PrivateLeaguesSync status: OTHER_ERROR_STATUS - "+status);
			return;
		}
	}

	/**
	 * Parse the verprivada.php per extreure'n els equips de la lliga privada
	 * passada pel que fa a punts.
	 * 
	 * @return true si no hi ha hagut error, altrament false.
	 */
	@SuppressWarnings("rawtypes")
	public boolean getPrivateLeagueTeams(PrivateLeague pl) throws Exception {
		// si no tenim privateLeagues, el creem buit i afegim la que ens passen
		if (privateLeagues == null) {
			privateLeagues = new ArrayList<PrivateLeague>();
			privateLeagues.add(pl);
		}

		HashMap<String, Team> teams = new HashMap<String, Team>();

		HttpGet ltHttpGet = new HttpGet(PRIVATE_LEAGUE_TEAMS + "?id_pri="
				+ pl.getId());
		HttpResponse response = client.execute(ltHttpGet);
		HtmlCleaner cleaner = new HtmlCleaner();

		ByteArrayOutputStream os = new ByteArrayOutputStream();
		response.getEntity().writeTo(os);
		String leagueTeamsPage = os.toString(HTTP.ISO_8859_1);
		TagNode node = cleaner.clean(leagueTeamsPage);

		NumberFormat nf = NumberFormat.getInstance(new Locale("es", "ES"));

		// cerquem la jornada de la lliga privada
		Object[] font = node.evaluateXPath(PRIVATE_LEAGUE_DAY_XPATH);
		int day = -1;
		if( font.length == 0 )
		{
			Log.d(TAG,"Error parsing verprivada.php... no day found");
			return false;
		}
		TagNode fontTag = (TagNode) font[0];
		// children de font, el b
		for (Object bTag: fontTag.getChildren())
		{
			TagNode bTagNode = (TagNode)bTag;
			if (!"b".equals((bTagNode).getName()) )
				continue;
			
			for (Object bContent: bTagNode.getChildren())
			{
				if( bContent instanceof ContentNode )
				{
					String tmpDay = ((ContentNode)bContent).toString();
					Integer dayObject = Integer.valueOf(0);
					Pattern p = Pattern.compile("(\\S*)\\s-\\sJornada\\s(\\S*)");
       				Matcher m = p.matcher(tmpDay);
       				if( m.find() ) 
       				{
       					try{
       						String dayParsed = m.group(2);
       						String lliga = m.group(1);
       						Log.d(TAG,"getPrivateLeagueTeams tmpDay: "+tmpDay+", lliga: "+lliga+", dayParsed: "+dayParsed);
       						dayObject = Integer.valueOf(nf.parse(dayParsed).intValue());
           				}catch(ParseException pe){
           					dayObject = Integer.valueOf("0");
           				}
       				}
       				day = dayObject.intValue();
       				Log.d(TAG,"PrivateLeagueSync getPrivateLeagueTeams parsing day: "+day);
				}
			}
			
		}

		// cerquem els equips de la lliga
		Object[] tdLT = node.evaluateXPath(PRIVATE_LEAGUE_TEAMS_XPATH);
		if (tdLT.length == 0) {
			Log.d(TAG,"Error parsing verprivada.php... no list of team found");
			return false;
		}
		TagNode tagLTHeader = (TagNode) tdLT[0];
		TagNode tagLTTable = tagLTHeader.getParent().getParent();

		// llistem els equips, diferents trs
		for (Object objTr : tagLTTable.getChildren()) {
			// descartem el tr del titular
			if (tagLTHeader.getParent().equals(objTr))
				continue;

			// els tds
			List tds = ((TagNode) objTr).getChildren();

			// el nom de l'equip sera la key del HashMap
			String name = null;

			// segon td
			TagNode td1 = (TagNode) tds.toArray()[1];
			for (Object td1Child : td1.getChildren()) {
				if (td1Child instanceof ContentNode) {
					name = td1Child.toString();
					continue;
				}
			}

			// si no trobem el nom de l'equip, continuem i descartem la linia
			if (name == null) {
				Log.d("supermanager",
						"Error parsing private league teams, team name not found.");
				continue;
			}

			// creem equip per omplir-lo
			Team t = new Team();
			t.setName(name.trim());
			t.setDay(day);

			// tercer td
			TagNode td2 = (TagNode) tds.toArray()[2];
			for (Object td2Child : td2.getChildren()) {
				if (td2Child instanceof ContentNode) {
					String manager = "unknown";
					String city = "unknown";
					Pattern p = Pattern.compile("([^\\(]*)\\(([^\\)]*)\\)");
					Matcher m = p.matcher(td2Child.toString());
					if (m.find()) {
						manager = m.group(1);
						city = m.group(2);
					}
					t.setManager(manager.trim());
					t.setCity(city.trim());
					continue;
				}
			}

			// quart td
			TagNode td3 = (TagNode) tds.toArray()[3];
			for (Object td3Child : td3.getChildren()) {
				if (td3Child instanceof ContentNode) {
					Float points;
					try {
						points = Float.valueOf(nf.parse(td3Child.toString())
								.floatValue());
					} catch (ParseException pe) {
						points = Float.valueOf("0");
					}
					t.setPoints(points);
					continue;
				}
			}

			// guardem l'equip parsejat al HashMap
			teams.put(name.trim(), t);
		}

		// guardem els equips a la lliga privada
		pl.setTeams(teams);

		return true;
	}

	/**
	 * Parse the verprivada.php per extreure'n els equips de la lliga privada
	 * passada i la puntuacio general.
	 * 
	 * @return true si no hi ha hagut error, altrament false.
	 */
	@SuppressWarnings("rawtypes")
	public boolean getPrivateLeagueTeamsGeneral(PrivateLeague pl)
			throws Exception {
		HashMap<String, Team> teams = null;

		// si no tenim privateLeagues, el creem buit i afegim la que ens passen
		if (privateLeagues == null) {
			privateLeagues = new ArrayList<PrivateLeague>();
			privateLeagues.add(pl);
		}
		teams = pl.getTeams();

		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("id_pri", pl.getId()));
		nvps.add(new BasicNameValuePair("tipo", "valoracion"));

		HttpPost ltHttpPost = new HttpPost(PRIVATE_LEAGUE_TEAMS);
		ltHttpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.ISO_8859_1));
		HttpResponse response = client.execute(ltHttpPost);
		HtmlCleaner cleaner = new HtmlCleaner();

		ByteArrayOutputStream os = new ByteArrayOutputStream();
		response.getEntity().writeTo(os);
		String leagueTeamsPage = os.toString(HTTP.ISO_8859_1);
		TagNode node = cleaner.clean(leagueTeamsPage);

		NumberFormat nf = NumberFormat.getInstance(new Locale("es", "ES"));
		
		// cerquem els equips de la lliga
		Object[] tdLT = node.evaluateXPath(PRIVATE_LEAGUE_TEAMS_XPATH);
		if (tdLT.length == 0) {
			Log.d("supermanager",
					"Error parsing verprivada.php... no list of team found");
			return false;
		}
		TagNode tagLTHeader = (TagNode) tdLT[0];
		TagNode tagLTTable = tagLTHeader.getParent().getParent();

		// llistem els equips, diferents trs
		for (Object objTr : tagLTTable.getChildren()) {
			// descartem el tr del titular
			if (tagLTHeader.getParent().equals(objTr))
				continue;

			// els tds
			List tds = ((TagNode) objTr).getChildren();

			// nom de l'equip per identificar-lo i continuar omplint dades
			String name = null;

			// segon td
			TagNode td1 = (TagNode) tds.toArray()[1];
			for (Object td1Child : td1.getChildren()) {
				if (td1Child instanceof ContentNode) {
					name = td1Child.toString();
					continue;
				}
			}

			// error, no trobem l'equip al llistat parsejat a
			// getPrivateLeagueTeams
			if (name == null) {
				Log.d("supermanager",
						"Error parsing private league teams general, team name not found.");
				continue;
			}
			// creem equip per omplir-lo
			Team t = teams.get(name.trim());
			
			// tercer td
			TagNode td2 = (TagNode) tds.toArray()[2];
			for (Object td2Child : td2.getChildren()) {
				if (td2Child instanceof ContentNode) {
					String manager = "unknown";
					String city = "unknown";
					Pattern p = Pattern.compile("([^\\(]*)\\(([^\\)]*)\\)");
					Matcher m = p.matcher(td2Child.toString());
					if (m.find()) {
						manager = m.group(1);
						city = m.group(2);
					}
					t.setManager(manager.trim());
					t.setCity(city.trim());
					continue;
				}
			}

			// quart td
			TagNode td3 = (TagNode) tds.toArray()[3];
			for (Object td3Child : td3.getChildren()) {
				if (td3Child instanceof ContentNode) {
					Float general;
					try {
						general = Float.valueOf(nf.parse(td3Child.toString())
								.floatValue());
					} catch (ParseException pe) {
						general = Float.valueOf("0");
					}
					t.setGeneral(general);
					continue;
				}
			}
		}

		// guardem els equips a la lliga privada
		pl.setTeams(teams);

		return true;
	}

	/**
	 * Parse the verprivada.php per extreure'n els equips de la lliga privada
	 * passada i la puntuacio boker.
	 * 
	 * @return true si no hi ha hagut error, altrament false.
	 */
	@SuppressWarnings("rawtypes")
	public boolean getPrivateLeagueTeamsBroker(PrivateLeague pl)
			throws Exception {
		HashMap<String, Team> teams = null;

		// si no tenim privateLeagues, el creem buit i afegim la que ens passen
		if (privateLeagues == null) {
			privateLeagues = new ArrayList<PrivateLeague>();
			privateLeagues.add(pl);
		}
		teams = pl.getTeams();

		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("id_pri", pl.getId()));
		nvps.add(new BasicNameValuePair("tipo", "broker"));

		HttpPost ltHttpPost = new HttpPost(PRIVATE_LEAGUE_TEAMS);
		ltHttpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.ISO_8859_1));
		HttpResponse response = client.execute(ltHttpPost);
		HtmlCleaner cleaner = new HtmlCleaner();

		ByteArrayOutputStream os = new ByteArrayOutputStream();
		response.getEntity().writeTo(os);
		String leagueTeamsPage = os.toString(HTTP.ISO_8859_1);
		TagNode node = cleaner.clean(leagueTeamsPage);

		NumberFormat nf = NumberFormat.getInstance(new Locale("es", "ES"));
		
		// cerquem els equips de la lliga
		Object[] tdLT = node.evaluateXPath(PRIVATE_LEAGUE_TEAMS_XPATH);
		if (tdLT.length == 0) {
			Log.d("supermanager",
					"Error parsing verprivada.php... no list of team found");
			return false;
		}
		TagNode tagLTHeader = (TagNode) tdLT[0];
		TagNode tagLTTable = tagLTHeader.getParent().getParent();

		// llistem els equips, diferents trs
		for (Object objTr : tagLTTable.getChildren()) {
			// descartem el tr del titular
			if (tagLTHeader.getParent().equals(objTr))
				continue;

			// els tds
			List tds = ((TagNode) objTr).getChildren();

			// nom de l'equip com a key per trobar-lo al array de teams
			String name = null;

			// segon td
			TagNode td1 = (TagNode) tds.toArray()[1];
			for (Object td1Child : td1.getChildren()) {
				if (td1Child instanceof ContentNode) {
					name = td1Child.toString();
					continue;
				}
			}

			// error, no trobem l'equip al llistat parsejat a
			// getPrivateLeagueTeams
			if (name == null) {
				Log.d("supermanager",
						"Error parsing private league teams broker, team name not found.");
				continue;
			}
			// creem equip per omplir-lo
			Team t = teams.get(name.trim());

			// tercer td
			TagNode td2 = (TagNode) tds.toArray()[2];
			for (Object td2Child : td2.getChildren()) {
				if (td2Child instanceof ContentNode) {
					String manager = "unknown";
					String city = "unknown";
					Pattern p = Pattern.compile("([^\\(]*)\\(([^\\)]*)\\)");
					Matcher m = p.matcher(td2Child.toString());
					if (m.find()) {
						manager = m.group(1);
						city = m.group(2);
					}
					t.setManager(manager.trim());
					t.setCity(city.trim());
					continue;
				}
			}

			// quart td
			TagNode td3 = (TagNode) tds.toArray()[3];
			for (Object td3Child : td3.getChildren()) {
				if (td3Child instanceof ContentNode) {
					Integer broker;
					try {
						broker = Integer.valueOf(nf.parse(td3Child.toString())
								.intValue());
					} catch (ParseException pe) {
						broker = Integer.valueOf("0");
					}
					t.setBroker(broker);
					continue;
				}
			}
		}

		// guardem els equips a la lliga privada
		pl.setTeams(teams);

        return true;
	}

	/**
	 * Guardar les dades trobades a DB.
	 */
	protected void onPostExecute(Uri uri) 
	{
		// tractem cada lliga privada
		Log.d(TAG, "Parsed " + privateLeagues.size()
				+ " private leagues, going to insert/update");
		for (PrivateLeague pl : privateLeagues)
		{
			// insert or update la private league
			String lastPathSegment = insertOrUpdatePrivateLeague(uri, pl);
			
			// lliga sense equips inscrits
			if (pl.getTeams() == null) {
				Log.d(TAG, "Private leagues [" + pl.getName() + "] has no teams");
				continue;
			}

			// insertem els equips de la lliga privada
			for (Team team : pl.getTeams().values()) 
			{
				insertOrUpdatePrivateLeagueTeam(lastPathSegment, pl, team);
			}
		}
	}
	
	/**
	 * Insert or Update PrivateLeague as needed.
	 * @param uri
	 * @param pl
	 * @return
	 */
	private String insertOrUpdatePrivateLeague(Uri uri, PrivateLeague pl)
	{
		// insertem la lliga privada
		ContentValues values = new ContentValues();
		values.put(Supermanager.PrivateLeague.NAME, pl.getName());
		values.put(Supermanager.PrivateLeague.NUMBER_OF_TEAMS,
				pl.getNumberOfTeams());
		values.put(Supermanager.PrivateLeague.ID_PRIV, pl.getId());
		
		Uri plUri = Supermanager.PrivateLeague.CONTENT_URI;
		String lastPathSegment = "0";
		
		// si update no retorna 1 reg, llavors insert
		if( service.getContentResolver().update(uri, 
				values, 
				Supermanager.PrivateLeague.ID_PRIV+" = ? ", 
				new String[]{pl.getId()}) == 0 )
		{
			plUri = service.getContentResolver().insert(uri, values);
			lastPathSegment = plUri.getLastPathSegment();
			Log.d(TAG, "Inserting private league [" + pl.getName()
					+ "] with Uri [" + plUri + "] lastPathSegment ["
					+ lastPathSegment + "]");
		}
		else
		{
			Cursor cursor = service.getContentResolver().
				query(Supermanager.PrivateLeague.CONTENT_URI, 
					  Supermanager.PrivateLeague.PROJECTION, 
					  Supermanager.PrivateLeague.ID_PRIV+" = ? ", 
					  new String[]{pl.getId()}, 
					  Supermanager.PrivateLeague.DEFAULT_SORT_ORDER);
			
			if( cursor.moveToFirst() )
			{
				lastPathSegment = ""+cursor.getLong(0);
				plUri = ContentUris.withAppendedId(Supermanager.PrivateLeague.CONTENT_URI, cursor.getLong(0));
			}
			Log.d(TAG, "Updating private league [" + pl.getName()
					+ "] with Uri [" + plUri + "] lastPathSegment ["
					+ lastPathSegment + "]");
		}
		
		return lastPathSegment;
	}
	
	private Uri insertOrUpdatePrivateLeagueTeam(String lastPathSegment, PrivateLeague pl, Team team)
	{
		// insertem l'equip
		ContentValues teamValues = new ContentValues();
		teamValues.put(Supermanager.PrivateLeagueTeam._PRIVATE_LEAGUE_ID, lastPathSegment);
		teamValues.put(Supermanager.PrivateLeagueTeam.NAME, team.getName());
		teamValues.put(Supermanager.PrivateLeagueTeam.DAY, team.getDay());
		teamValues.put(Supermanager.PrivateLeagueTeam.MANAGER, team.getManager());
		teamValues.put(Supermanager.PrivateLeagueTeam.CITY, team.getCity());
		teamValues.put(Supermanager.PrivateLeagueTeam.ID_PRIV, pl.getId());
		teamValues.put(Supermanager.PrivateLeagueTeam.POINTS, team.getPoints());
		teamValues.put(Supermanager.PrivateLeagueTeam.GENERAL, team.getGeneral());
		teamValues.put(Supermanager.PrivateLeagueTeam.BROKER, team.getBroker());
		
		Uri tUri = Supermanager.PrivateLeagueTeam.CONTENT_URI;
		// si update no retorna 1 reg, llavors insert
		if( service.getContentResolver().update(Supermanager.PrivateLeagueTeam.CONTENT_URI, 
				teamValues, 
				Supermanager.PrivateLeagueTeam.ID_PRIV+" = ? AND "+
				Supermanager.PrivateLeagueTeam.NAME+" = ? AND "+
				Supermanager.PrivateLeagueTeam.DAY+" = ? ", 
				new String[]{pl.getId(), team.getName(), team.getDay().toString()}) == 0 )
		{
			tUri = service.getContentResolver().insert(
					PrivateLeagueTeam.CONTENT_URI, teamValues);
			Log.d(TAG, "Inserting private league team [" + team.getName() + "] of league ["
					+ pl.getName() + "] with Uri [" + tUri + "]");
		}
		else
		{
			Cursor cursor = service.getContentResolver().
			query(Supermanager.PrivateLeagueTeam.CONTENT_URI, 
				  Supermanager.PrivateLeagueTeam.PROJECTION, 
				  Supermanager.PrivateLeagueTeam.ID_PRIV+" = ? AND "+
				  Supermanager.PrivateLeagueTeam.NAME+" = ? AND "+
				  Supermanager.PrivateLeagueTeam.DAY+" = ? ", 
				  new String[]{pl.getId(), team.getName(), team.getDay().toString()}, 
				  Supermanager.PrivateLeagueTeam.DEFAULT_SORT_ORDER);
		
			if( cursor.moveToFirst() )
			{
				tUri = ContentUris.withAppendedId(Supermanager.PrivateLeagueTeam.CONTENT_URI, cursor.getLong(0));
		
				Log.d(TAG, "Updating private league team [" + team.getName() + "] of league ["
						+ pl.getName() + "] with Uri [" + tUri + "]");
			}
		}
		
		return tUri;
	}
}
